package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public void submit(@RequestBody Orders orders) {
        //本地线程获取用户ID
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ShoppingCart> eq = queryWrapper.eq(ShoppingCart::getId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(queryWrapper);

        // 2、查询用户数据 select * from user where id = ?
        User user = userMapper.selectById(userId);

        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        //订单号
        Long orderId = IdWorker.getId();
        //总价
        BigDecimal amount = new BigDecimal(0);

        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : shoppingCarts) {
            // ShoppingCart shoppingCart --> OrderDetail orderDetail
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(shoppingCart, orderDetail);

            // orderId单独设置

            orderDetail.setOrderId(orderId);

            // amount 金额单独设置 数量  *  单价

            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());

            orderDetail.setAmount(price.multiply(number));

            amount.add(orderDetail.getAmount());

            orderDetailMapper.insert(orderDetail);
        }
        // 5、保存订单数据，有许多数据需要单独设置
        //订单id
        orders.setId(orderId);
        //订单创建时间
        orders.setOrderTime(LocalDateTime.now());
        //订单结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //总金额
        orders.setAmount(amount);
        //用户id
        orders.setUserId(userId);
        //订单号
        orders.setNumber(String.valueOf(orderId));
        //用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //收货人联系电话
        orders.setPhone(addressBook.getPhone());
        //省+市+区域+详细地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + addressBook.getDetail() == null ? "" : addressBook.getDetail());
        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(qw);
    }
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize){
        //构造分页查询器
        Page pageInfo = new Page(page,pageSize);

        orderService.page(pageInfo);

        List<Orders> ordersList = pageInfo.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders orders : ordersList) {
            Long id = orders.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            ordersDto.setOrderDetails(orderDetailList);

            ordersDto.setOrderDetails(orderDetailList);

            ordersDtos.add(ordersDto);
        }
        Map map = new HashMap();
        int total = (int) pageInfo.getTotal();
        map.put("total",total);
        map.put("records",ordersDtos);
        return R.success(map);
    }

}
